<template>
  <div class="apply-container">
    <!-- 主布局：左右分栏 -->
    <div class="main-layout">
      <!-- 左侧：窄版申请流程 -->
      <div class="process-box">
        <h2 class="box-title">申请流程</h2>
        <div class="process-steps vertical">
          <div class="step active">
            <div class="step-content">
              <div class="step-icon-container">
                <el-icon class="step-icon">
                  <Edit />
                </el-icon>
              </div>
              <div class="step-text">
                <div class="step-title">提交申请</div>
                <div class="step-desc">填写申请信息</div>
              </div>
            </div>
            <div class="step-arrow"></div>
          </div>
          <div class="step">
            <div class="step-content">
              <div class="step-icon-container">
                <el-icon class="step-icon">
                  <User />
                </el-icon>
              </div>
              <div class="step-text">
                <div class="step-title">教师审核</div>
                <div class="step-desc">1-2个工作日</div>
              </div>
            </div>
            <div class="step-arrow"></div>
          </div>
          <div class="step">
            <div class="step-content">
              <div class="step-icon-container">
                <el-icon class="step-icon">
                  <OfficeBuilding />
                </el-icon>
              </div>
              <div class="step-text">
                <div class="step-title">院级审核</div>
                <div class="step-desc">3-5个工作日</div>
              </div>
            </div>
            <div class="step-arrow"></div>
          </div>
          <div class="step">
            <div class="step-content">
              <div class="step-icon-container">
                <el-icon class="step-icon">
                  <Finished />
                </el-icon>
              </div>
              <div class="step-text">
                <div class="step-title">完成认定</div>
                <div class="step-desc">学分入库</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧：申请表单 -->
      <div class="form-box">
        <h2 class="box-title">提交申请材料</h2>
        <el-form ref="applyForm" :model="data.form" :rules="data.rules" label-position="top" class="compact-form">
          <!-- 修改后的申请类型行 -->
          <el-form-item>
            <div class="application-info-row">
              <!-- 申请类型 -->
              <div class="info-item type-item">
                <div class="info-label">创新创业活动分类类型</div>
                <el-select v-model="data.form.typeId" placeholder="请选择类型" @change="handleTypeChange"
                  class="info-select type-select">
                  <el-option v-for="item in typeOptions" :key="item.typeId" :label="item.name" :value="item.typeId" />
                </el-select>
              </div>

              <!-- 具体活动 -->
              <div class="info-item activity-item">
                <div class="info-label">创新创业活动项目</div>
                <el-select v-model="data.form.actId" placeholder="请先选择类型" :disabled="!data.form.typeId"
                  class="info-select activity-select">
                  <el-option v-for="activity in filteredActivities" :key="activity.actId" :label="activity.actName"
                    :value="activity.actId" />
                </el-select>
              </div>

              <!-- 获得学分 -->
              <div class="info-item credit-item">
                <div class="info-label">获得学分</div>
                <div class="credit-display">
                  {{ data.form.creditCount || '请先选择活动' }}
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="上传证明材料" required class="upload-form-item" prop="appData">
            <el-upload id="fileInput" class="upload-demo" drag :file-list="fileList" :action="data.uploadAction"
              :before-upload="beforeUpload" :on-change="handleChange" :on-remove="handleRemove"
              :limit="uploadConfig.maxFiles" :on-success="handleSuccess" :on-error="handleError"
              :on-exceed="handleExceed" multiple>
              <el-icon class="upload-icon">
                <Upload />
              </el-icon>
              <div class="upload-text">点击或拖拽文件到这里上传</div>
              <div class="upload-tip">
                支持 {{ uploadConfig.allowedTypes.join('/') }} 格式，
                单个文件不超过 {{ uploadConfig.maxSize }}MB，
                最多 {{ uploadConfig.maxFiles }} 个文件
              </div>
            </el-upload>
          </el-form-item>

          <div class="form-footer">
            <el-button type="primary" size="large" @click="handleSubmitApply" class="submit-btn">
              <el-icon>
                <Promotion />
              </el-icon>
              <span>提交申请</span>
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, computed, watch, reactive, onMounted } from 'vue'
import {
  Edit, User, OfficeBuilding, Finished,
  Upload, Promotion, Document, View, Delete
} from '@element-plus/icons-vue'
import alovaInstance from '@/utils/request'
import { useRouter } from 'vue-router';

const router = useRouter();
const data = reactive({
  typeId: '',
  actId: '',
  form: {
    appData: [] // 存储上传文件的URL
  },
  rules: {
    typeId: [{ required: true, message: '请选择创新创业类型', trigger: 'blur' }],
    actId: [{ required: true, message: '请选择创新创业活动项', trigger: 'blur' }],
    creditCount: [{ required: true, message: '申请学分为空', trigger: 'blur' }],
    appData: [{ required: true, message: '请上传申请材料', trigger: 'blur' }]
  },
  uploadAction: 'http://localhost:9090/files/upload' // 文件上传接口地址
})

const applyForm = ref();
const fileList = ref([])
// 完整的活动数据
const activityData = ref([])
const typeOptions = ref([])
const loading = ref(false)      // 加载状态
const user = JSON.parse(window.localStorage.getItem("credit-system-user"));

// 文件上传配置
const uploadConfig = {
  maxSize: 5, // MB
  allowedTypes: ['image/jpeg', 'image/png', 'application/pdf'],
  maxFiles: 3
}

onMounted(() => {
  loadTypes()
})

// 计算属性：获取当前选中类型下的活动
const filteredActivities = computed(() => {
  if (!data.form.typeId) return []
  return activityData.value.filter(item => item.typeId == data.form.typeId) // 注意转为相同类型
})

// 类型变更处理
const handleTypeChange = () => {
  data.form.actId = ''       // 清空已选活动
  data.form.creditCount = '' // 清空学分
  loadActivities()           // 重新加载活动
}

// 监听活动选择变化
watch(() => data.form.actId, (newVal) => {
  if (newVal) {
    const selected = activityData.value.find(a => a.actId == newVal) // 注意转为相同类型
    data.form.creditCount = selected?.creditCount || ''
  }
})

const loadTypes = () => {
  loading.value = true
  // 加载活动类型
  alovaInstance.Get('/collegeAdminActiveType/selectActiveTypeList', {
    params: {
      typeId: data.typeId
    }
  }).then(res => {
    if (res.code === '200') {
      typeOptions.value = res.data || []
      console.log('查询活动分类成功！')
      console.log('加载的类型选项:', typeOptions.value)
    } else {
      console.log(res.msg || '查询活动分类失败')
    }
  }).catch(error => {
    console.error('请求失败:', error);
    console.log(error.message || '请求活动分类数据失败');
  });
}

// 加载活动数据
const loadActivities = () => {
  if (!data.form.typeId) return
  loading.value = true
  alovaInstance.Get('/collegeAdminActiveCredit/selectActiveCreditList', {
    params: {
      typeId: data.form.typeId  // 只传当前选中的类型ID
    }
  })
    .then(res => {
      if (res.code === '200') {
        activityData.value = res.data || []
        console.log('活动数据:', activityData.value)
        console.log('查询活动数据成功！')
      } else {
        console.log(res.msg || '获取活动数据失败')
      }
    })
    .catch(error => {
      console.error('请求失败:', error)
      console.log(error.message || '请求活动数据失败')
    })
    .finally(() => loading.value = false)
}

// 上传前校验文件
const beforeUpload = (file) => {
  // 检查文件类型
  const isPDF = file.type === 'application/pdf';
  const isWord = file.type.includes('word') || file.type.includes('excel');
  const isImage = file.type.includes('image');

  if (!(isPDF || isWord || isImage)) {
    ElMessage.error('仅支持PDF、Word和图片文件上传');
    return false;
  }

  // 检查文件大小 (5MB = 5 * 1024 * 1024)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过5MB');
    return false;
  }

  return true;
};

// 文件超出限制处理
const handleExceed = (files, fileList) => {
  ElMessage.warning(`上传失败！最多只能上传3个文件`);
};

// 文件移除处理
const handleRemove = (file) => {
  ElMessage.info(`已移除文件: ${file.name}`);
  // 从表单数据中移除对应的文件URL
  data.form.appData = data.form.appData.filter(url => url !== file.response);
};

// 上传成功处理
const handleSuccess = (response, file) => {
  ElMessage.success(`文件 ${file.name} 上传成功`);
  // 将上传成功的文件URL添加到表单数据中
  console.log(response)
  data.form.appData.push(response.data);
};

// 上传失败处理
const handleError = (error, file) => {
  ElMessage.error(`文件 ${file.name} 上传失败，请重试`);
  console.error('文件上传失败:', error);
};

// 处理提交申请（包含二次确认）
const handleSubmitApply = () => {
  // 先进行表单验证
  applyForm.value.validate((valid) => {
    if (valid) {
      // 显示二次确认弹窗
      ElMessageBox.confirm(
        '确认提交当前申请吗？提交后将无法修改，进入等待审核',
        '提示',
        {
          confirmButtonText: '确 认',
          cancelButtonText: '取 消',
          type: 'warning'
        }
      ).then(() => {
        // 用户点击确认后的处理
        submitApply();
      }).catch(() => {
        // 用户点击取消后的处理（无需操作，直接返回）
        ElMessage.warning('已取消提交申请');
      });
    }
  });
};

// 提交表单（包含文件上传）
const submitApply = async () => {
  // 表单验证
  if (!data.form.typeId) {
    ElMessage.warning('请选择申请类型')
    return
  }
  if (!data.form.actId) {
    ElMessage.warning('请选择具体活动')
    return
  }

  // 将文件列表url数组转换为字符串
  data.form.appData = data.form.appData.join(',');
  data.form.stuId = user.stuId;
  alovaInstance.Post('/applicationRecord/submitApply', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success({
        message: '提交成功，即将跳转到申请记录',
        duration: 1500,
        onClose: () => {
          // 使用路由名称跳转（推荐方式）
          router.push({ name: 'sApplyRecord' });
        }
      });
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message || '网络错误，请稍后重试');
  });
  // setTimeout(() => { location.reload(); }, 500);
}

</script>

<style scoped>
/* 文件预览列表样式 */
.file-preview-list {
  margin-top: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.file-preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.file-preview-item:last-child {
  border-bottom: none;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
  overflow: hidden;
}

.file-info .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.file-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

.file-actions {
  margin-left: 10px;
}

.type-select {
  min-width: 180px;
}

.activity-select {
  min-width: 240px;
}

.application-info-row {
  display: flex;
  gap: 29px;
  align-items: flex-start;
}

.info-item {
  flex: none;
}

.type-item {
  width: 300px;
}

.activity-item {
  width: 300px;
}

.credit-item {
  width: 300px;
}

.info-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

.info-label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
  display: inline;
}

.info-select {
  width: 100%;
}

.info-select :deep(.el-input__inner) {
  height: 42px;
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.5;
}

.credit-display {
  padding: 0 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #409eff;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 上传区域专用样式 - 填满剩余空间 */
.upload-form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  margin-bottom: 0;
}

.upload-form-item :deep(.el-form-item__content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.upload-demo {
  width: 100%;
  height: 100%;
  min-height: 300px;
  display: flex;
  flex-direction: column;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  transition: all 0.3s;
  box-sizing: border-box;
  background-color: #fafafa;
}

.upload-demo:hover {
  border-color: #409eff;
  background-color: #f5f9ff;
}

:deep(.el-upload) {
  flex: 1;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-upload-dragger) {
  flex: 1;
  width: 100%;
  height: 100%;
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
}

.upload-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #409eff;
}

.upload-text {
  font-size: 20px;
  margin-bottom: 12px;
  color: #333;
  font-weight: 500;
  text-align: center;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
  text-align: center;
  max-width: 80%;
  line-height: 1.5;
}

/* 文件列表样式 */
:deep(.el-upload-list) {
  width: 100%;
  margin-top: 15px;
  max-height: 200px;
  overflow-y: auto;
  flex-shrink: 0;
}

:deep(.el-upload-list__item) {
  transition: all 0.3s;
  border-radius: 6px;
  padding: 12px 15px;
  margin-bottom: 8px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 底部提交按钮 */
.form-footer {
  margin-top: auto;
  padding-top: 20px;
}

.submit-btn {
  width: 100%;
  height: 52px;
  font-size: 18px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .upload-demo {
    min-height: 250px;
  }

  :deep(.el-upload-dragger) {
    padding: 20px;
  }

  .upload-icon {
    font-size: 54px;
  }

  .upload-text {
    font-size: 18px;
  }
}

/* 以下是原有保持不变的其他样式 */
.apply-container {
  max-width: 1600px;
  margin: 20px auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: auto;
  min-height: 90vh;
  overflow: visible;
}

.main-layout {
  display: flex;
  gap: 20px;
  align-items: stretch;
  min-height: 0;
}

.process-box {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 25px;
  width: 280px;
  display: flex;
  flex-direction: column;
  height: auto;
  flex-shrink: 0;
}

.form-box {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 25px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.box-title {
  font-size: 22px;
  color: #333;
  margin-top: 0;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
  font-weight: 600;
  display: flex;
  align-items: center;
  text-align: center;
}

.process-steps.vertical {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.step {
  position: relative;
  padding: 10px 0;
  width: 100%;
}

.step-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s;
  width: 100%;
  box-sizing: border-box;
}

.step.active .step-content {
  background-color: #f5f9ff;
  border-left: 4px solid #409eff;
}

.step:not(:last-child):after {
  content: '';
  position: absolute;
  bottom: -15px;
  left: 30px;
  width: 2px;
  height: 15px;
  background-color: #e8e8e8;
}

.step-icon {
  font-size: 28px;
  margin-bottom: 12px;
  color: #c0c4cc;
}

.step-icon-container {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #f0f5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.step.active .step-icon {
  color: #409eff;
}

.step-text {
  text-align: center;
  width: 100%;
}

.step-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.step-desc {
  font-size: 15px;
  color: #666;
  line-height: 1.5;
}

.step-arrow {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: 20px;
  background-color: #e8e8e8;
}

.step.active .step-arrow {
  background-color: #409eff;
}

.step:last-child .step-arrow {
  display: none;
}

.compact-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .apply-container {
    height: auto;
    overflow: visible;
  }
}

@media (max-width: 992px) {
  .application-info-row {
    flex-direction: column;
    gap: 16px;
  }

  .type-item,
  .activity-item,
  .credit-item {
    width: 100%;
  }

  .credit-display {
    justify-content: flex-start;
  }

  .main-layout {
    flex-direction: column;
  }

  .process-box,
  .form-box {
    width: 100%;
    padding: 25px;
    position: relative;
  }
}

@media (max-width: 768px) {
  .box-title {
    text-align: center;
    width: 100%;
    margin-bottom: 20px;
  }

  .step {
    flex: 0 0 100%;
  }
}
</style>